package com.yunshipei.ui.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshipei.base.BaseActivity;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.common.Globals;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.ShareInfoModel;
import com.yunshipei.model.ShareItemEnum;
import com.yunshipei.model.ShareModel;
import com.yunshipei.ui.adapter.YspConversationListAdapter;
import com.yunshipei.utils.CharacterParser;
import com.yunshipei.utils.ShareLinkImage.LinkPreviewCallback;
import com.yunshipei.utils.ShareLinkImage.SourceContent;
import com.yunshipei.utils.ShareLinkImage.TextCrawler;
import com.yunshipei.utils.ShareUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import io.rong.app.model.GroupCreateInfo;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * Created by cike on 16/8/17.
 */
public class ShareActivity extends BaseActivity implements ShareUtil.OnSendMessageSuccessListener {
    private final static int REQUEST_CODE = 1;
    public final static int RESPONSE_CODE = 2;
    private ListView mListView;
    private EditText searchView;
    private TextView emptyText;
    private List<ShareModel> shareModels = new ArrayList<>();
    private YspConversationListAdapter yspAdapter;
    private ShareInfoModel shareInfoModel = null;
    private YspTitleBar titleBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share_main);
        initView();
        initData();
    }

    private void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getBundleExtra("shareInfo");
            shareInfoModel = (ShareInfoModel) bundle.getSerializable("shareInfo");
        }
        titleBar = (YspTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle("选择");
        emptyText = (TextView) findViewById(R.id.conversation_empty);
        searchView = (EditText) findViewById(R.id.share_search);
        mListView = (ListView) findViewById(R.id.conversation_list);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ShareModel shareModel = yspAdapter.getItem(position);
                ShareUtil shareUtil = new ShareUtil(ShareActivity.this);
                if (shareModel.getItemType() == ShareItemEnum.CONVERSATION) {
                    final Conversation data = (Conversation) shareModel.getItemContent();
                    if (data.getConversationType() == Conversation.ConversationType.GROUP) {
                        shareInfoModel.setShareModel(shareModel);
                        shareInfoModel.setType(Conversation.ConversationType.GROUP);
                        shareUtil.setData(shareInfoModel);
                    } else if (data.getConversationType() == Conversation.ConversationType.PRIVATE) {
                        io.rong.imlib.model.UserInfo userInfo = new DatabaseUtil().queryByUuid(data.getTargetId());
                        shareInfoModel.setShareModel(shareModel);
                        shareInfoModel.setType(Conversation.ConversationType.PRIVATE);
                        shareUtil.setData(shareInfoModel);
                    }
                    shareUtil.setOnDefineClickLisenter(ShareActivity.this);
                    shareUtil.showDialog();
                } else if (shareModel.getItemType() == ShareItemEnum.CONTACT) {
                    Intent intent = new Intent(ShareActivity.this, SeekContactsActivity.class);
                    intent.setAction(Globals.SHARE);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("shareInfoModel", shareInfoModel);
                    intent.putExtra("shareInfoModel", bundle);
                    startActivityForResult(intent, REQUEST_CODE);
                } else if (shareModel.getItemType() == ShareItemEnum.GROUP) {
                    Intent intent = new Intent(ShareActivity.this, GroupListActivity.class);
                    intent.setAction(Globals.SHARE);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("shareInfoModel", shareInfoModel);
                    intent.putExtra("shareInfoModel", bundle);
                    startActivityForResult(intent, REQUEST_CODE);
                }

            }
        });
        mListView.setEmptyView(emptyText);
    }

    private void initData() {
        shareModels.add(new ShareModel(ShareItemEnum.CONTACT, "通讯录"));
        shareModels.add(new ShareModel(ShareItemEnum.GROUP, "群组"));
        shareModels.add(new ShareModel(ShareItemEnum.SMALLTITLE, "最近聊天"));
        yspAdapter = new YspConversationListAdapter(this);
        RongIM.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                if (conversations != null) {
                    Iterator<Conversation> iterator = conversations.iterator();
                    ShareModel shareModel;
                    while (iterator.hasNext()) {
                        shareModel = new ShareModel();
                        shareModel.setItemType(ShareItemEnum.CONVERSATION);
                        Conversation data = iterator.next();
                        if (data.getConversationType() == Conversation.ConversationType.GROUP) {
                            GroupCreateInfo groupCreateInfo = new DatabaseUtil().findGroupById(data.getTargetId());
                            if (groupCreateInfo != null) {
                                shareModel.setName(groupCreateInfo.getName());
                                shareModel.setAvator(groupCreateInfo.getPortraitUri());
                                shareModel.setTargetId(groupCreateInfo.getId());
                                shareModel.setNember(groupCreateInfo.getNumber());
                                shareModel.setItemContent(data);
                                shareModels.add(shareModel);
                            }
                        } else if (data.getConversationType() == Conversation.ConversationType.PRIVATE) {
                            io.rong.imlib.model.UserInfo userInfo = new DatabaseUtil().queryByUuid(data.getTargetId());
                            if (userInfo != null) {
                                shareModel.setName(userInfo.getName());
                                shareModel.setAvator(String.valueOf(userInfo.getPortraitUri()));
                                shareModel.setTargetId(userInfo.getUserId());
                                shareModel.setNember(0);
                                shareModel.setItemContent(data);
                                shareModels.add(shareModel);
                            }
                        }

                    }
                }
                yspAdapter.addCollection(shareModels);
                mListView.setAdapter(yspAdapter);
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                yspAdapter.addCollection(shareModels);
                mListView.setAdapter(yspAdapter);
            }
        });
        initSearchEvent();
        //设置网页分享图片
        TextCrawler textCrawler = new TextCrawler();
        textCrawler.makePreview(new LinkPreviewCallback() {
            @Override
            public void onPre() {
            }
            @Override
            public void onPos(SourceContent sourceContent, boolean isNull) {
                if (sourceContent != null) {
                    //图片
                    Log.d("test", sourceContent.getImages().size() + "");
                    //主机地址
                    Log.d("test", sourceContent.getCannonicalUrl());
                    //网站描述
                    Log.d("test", sourceContent.getDescription());
                    //协议+主机
                    Log.d("test", sourceContent.getFinalUrl());
                    //网站标题
                    Log.d("test", sourceContent.getTitle());
                    //网页图片
                    if (sourceContent.getImages().size() > 0) {
                        String imageString = sourceContent.getImages().get(0);
                        Log.d("test", imageString);
                        shareInfoModel.setImageUri(imageString);
                    }
                }
            }

        }, shareInfoModel.getUrl());

    }

    private void initSearchEvent() {
        searchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SearchTask searchTask = new SearchTask();
                searchTask.execute(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public void onClick() {
        finish();
        showToast("已发送");

    }

    private void showToast(String string) {
        Toast.makeText(ShareActivity.this, string, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESPONSE_CODE)
            switch (requestCode) {
                case REQUEST_CODE:
                    finish();
                    break;
            }

    }

    private class SearchTask extends AsyncTask<String, Void, List<ShareModel>> {
        String searchKey;

        @Override
        protected List<ShareModel> doInBackground(String... params) {
            searchKey = params[0];
            List<ShareModel> filterDateList1 = new ArrayList<ShareModel>();
            if (TextUtils.isEmpty(searchKey)) {
                filterDateList1 = shareModels;
            } else {
                filterDateList1.clear();
                for (ShareModel shareModel : shareModels) {
                    if (shareModel.getItemType() == ShareItemEnum.CONVERSATION) {
                        String name = shareModel.getName();
                        if (!TextUtils.isEmpty(name) && compare(name, searchKey.toString())) {
                            if (!verdictSame(filterDateList1, shareModel)) {
                                filterDateList1.add(shareModel);
                            }
                        }
                    }
                }
            }
            return filterDateList1;
        }

        @Override
        protected void onPostExecute(List<ShareModel> filterDateList1) {
            if (filterDateList1 == null)
                return;
            yspAdapter.removeAll();
            yspAdapter.addCollection(filterDateList1);
            yspAdapter.notifyDataSetChanged();
            if (filterDateList1.size() <= 0) {
                emptyText.setVisibility(View.VISIBLE);
                emptyText.setText("无结果");
            }
        }
    }

    private SpannableString spannableStr(String key) {
        SpannableString spannableString = new SpannableString("未找到与\"" + key + "\"相关的结果");
        spannableString.setSpan(new ForegroundColorSpan(EnterConfig.getInstance().getGlobalColor()), 5, 5 + key.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    private boolean compare(String str1, String str2) {
        str1 = str1.toUpperCase();
        str2 = str2.toUpperCase();
        if (str1.indexOf(str2.toString()) != -1 || CharacterParser.getInstance().getSelling(str1).startsWith(str2.toString())) {
            return true;
        }
        return false;
    }

    private boolean verdictSame(List<ShareModel> list, ShareModel shareModel) {
        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (list.get(i).getTargetId().equals(shareModel.getTargetId())) {
                return true;
            }
        }
        return false;
    }
}
